<template>
  <div class="app-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" size="small">
        <el-form-item label="医生姓名">
          <el-input v-model="searchForm.doctorName" placeholder="请输入医生姓名" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="科室">
          <el-select v-model="searchForm.departmentId" placeholder="请选择科室" clearable>
            <el-option 
              v-for="dept in departments" 
              :key="dept.id" 
              :label="dept.name" 
              :value="dept.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button 
            type="success" 
            v-permission="'schedule:create'"
            @click="handleCreate"
          >
            <el-icon><Plus /></el-icon>新增排班
          </el-button>
          <el-button 
            type="warning" 
            v-permission="'schedule:create'"
            @click="handleBatchCreate"
          >
            <el-icon><Calendar /></el-icon>批量排班
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card shadow="never" class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        row-key="id"
        stripe
      >
        <el-table-column label="医生信息" min-width="150">
          <template #default="scope">
            <div>{{ scope.row.doctorName }}</div>
            <div class="text-secondary">{{ scope.row.doctorTitle }}</div>
            <div class="text-secondary">{{ scope.row.departmentName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="排班日期" min-width="120">
          <template #default="scope">
            <span>{{ formatDate(scope.row.date) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时间段" min-width="200">
          <template #default="scope">
            <div v-for="slot in scope.row.timeSlots" :key="slot.period" class="time-slot-item">
              <el-tag size="small" :type="getTimeSlotType(slot.period)">{{ slot.period }}</el-tag>
              <span class="time-slot-detail">{{ slot.startTime }}-{{ slot.endTime }}</span>
              <span class="capacity-info">
                (容量: {{ slot.capacity }})
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="剩余号源" min-width="120">
          <template #default="scope">
            <div v-for="(capacity, period) in scope.row.remainingCapacity" :key="period" class="remaining-item">
              <span>{{ period }}：</span>
              <el-tag :type="getCapacityTagType(capacity, scope.row.timeSlots.find(s => s.period === period)?.capacity)">
                {{ capacity }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="诊室" prop="room" min-width="120" />
        <el-table-column label="挂号类型" min-width="100">
          <template #default="scope">
            <el-tag>{{ scope.row.registrationType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="挂号费" min-width="80">
          <template #default="scope">
            <span>￥{{ scope.row.registrationFee }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small"
              @click="handleView(scope.row)"
              v-permission="'schedule:read'"
            >
              查看
            </el-button>
            <el-button 
              type="danger" 
              size="small"
              @click="handleCancel(scope.row)"
              v-permission="'schedule:delete'"
              :disabled="scope.row.status !== '正常'"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 取消排班对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消排班"
      width="500px"
    >
      <div class="cancel-warning">
        <el-alert
          title="取消排班将会影响已预约的患者"
          type="warning"
          description="取消排班后，该时段内的所有预约将被标记为已取消，并通知相关患者。"
          show-icon
          :closable="false"
        />
      </div>
      
      <el-form :model="cancelForm" ref="cancelFormRef" label-width="100px">
        <el-form-item label="取消原因" prop="reason" required>
          <el-input
            v-model="cancelForm.reason"
            type="textarea"
            placeholder="请输入取消原因"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel" :loading="cancelLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { scheduleAPI, departmentAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'
import { Plus, Calendar } from '@element-plus/icons-vue'

// 路由实例
const router = useRouter()

// 数据加载状态
const loading = ref(false)
const cancelLoading = ref(false)

// 科室列表
const departments = ref([])

// 日期快捷选项
const dateShortcuts = [
  {
    text: '本周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * start.getDay())
      return [start, end]
    },
  },
  {
    text: '下周',
    value: () => {
      const now = new Date()
      const start = new Date()
      start.setTime(now.getTime() + 3600 * 1000 * 24 * (7 - now.getDay()))
      const end = new Date()
      end.setTime(start.getTime() + 3600 * 1000 * 24 * 6)
      return [start, end]
    },
  },
  {
    text: '本月',
    value: () => {
      const now = new Date()
      const start = new Date(now.getFullYear(), now.getMonth(), 1)
      const end = new Date(now.getFullYear(), now.getMonth() + 1, 0)
      return [start, end]
    },
  },
]

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchFormRef = ref(null)
const searchForm = reactive({
  doctorName: '',
  departmentId: '',
  startDate: '',
  endDate: ''
})

// 日期范围
const dateRange = ref([])

// 监听日期范围变化
const updateDateRange = computed(() => {
  if (dateRange.value && dateRange.value.length === 2) {
    searchForm.startDate = dateRange.value[0]
    searchForm.endDate = dateRange.value[1]
  } else {
    searchForm.startDate = ''
    searchForm.endDate = ''
  }
})

// 取消排班对话框
const cancelDialogVisible = ref(false)
const cancelFormRef = ref(null)
const cancelForm = reactive({
  scheduleId: '',
  reason: ''
})
const currentSchedule = ref(null)

// 获取时间段标签类型
const getTimeSlotType = (period) => {
  switch (period) {
    case '上午':
      return 'success'
    case '下午':
      return 'warning'
    case '晚上':
      return 'info'
    default:
      return ''
  }
}

// 获取剩余号源标签类型
const getCapacityTagType = (remaining, total) => {
  if (!total) return 'info'
  const ratio = remaining / total
  if (ratio <= 0.2) return 'danger'
  if (ratio <= 0.5) return 'warning'
  return 'success'
}

// 获取科室列表
const getDepartments = async () => {
  try {
    const res = await departmentAPI.getDepartments()
    departments.value = res.data.items
  } catch (error) {
    console.error('获取科室列表失败', error)
  }
}

// 获取排班列表
const getSchedules = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    }
    
    // 移除空字段
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const res = await scheduleAPI.getSchedules(params)
    tableData.value = res.data.schedules
    total.value = res.data.total
  } catch (error) {
    console.error('获取排班列表失败', error)
    ElMessage.error('获取排班列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1
  getSchedules()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  dateRange.value = []
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getSchedules()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  getSchedules()
}

// 新增排班
const handleCreate = () => {
  router.push('/schedules/create')
}

// 批量排班
const handleBatchCreate = () => {
  router.push('/schedules/batch')
}

// 查看排班
const handleView = (row) => {
  router.push(`/schedules/detail/${row.id}`)
}

// 取消排班
const handleCancel = (row) => {
  currentSchedule.value = row
  cancelForm.scheduleId = row.id
  cancelForm.reason = ''
  cancelDialogVisible.value = true
}

// 确认取消排班
const confirmCancel = async () => {
  if (!cancelForm.reason) {
    ElMessage.warning('请输入取消原因')
    return
  }
  
  cancelLoading.value = true
  try {
    await scheduleAPI.deleteSchedule(cancelForm.scheduleId, { 
      reason: cancelForm.reason 
    })
    ElMessage.success('排班已取消')
    cancelDialogVisible.value = false
    getSchedules()
  } catch (error) {
    ElMessage.error(error.message || '取消排班失败')
  } finally {
    cancelLoading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  getSchedules()
  getDepartments()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  text-align: right;
  padding-top: 20px;
}

.text-secondary {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.time-slot-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.time-slot-detail {
  margin-left: 8px;
  color: #606266;
}

.capacity-info {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}

.remaining-item {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.remaining-item span {
  margin-right: 8px;
  color: #606266;
}

.cancel-warning {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 